<template>
    <div class="app-user">
     <Query
       :items="queryColumns"
       :initial-params="queryParams"
       @query="handleQuery"
     />
     <Table
       :table-columns="tableColumns"
       :table-loading="tableLoading"
       :table-data="tableData"
       :total="total"
       :showIndex="true"
       @pagination="handlePagination"
     >
     <template v-slot:tools>
       <el-button-group>
         <el-button type="primary" @click="handleAdd">添加用户</el-button>
       </el-button-group>
     </template>
       <template #opt="scope">
        <el-button type="primary" link @click="setRole(scope.row)">调整角色</el-button>
         <el-button type="danger" link @click="changeValue(scope.row)">移除</el-button>
       </template>
     </Table>
    </div>

    <el-dialog v-model="show" title="添加用户" width="500">
      <el-form :model="form" ref="formRef" :rules="rules">
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="account">
          <div class="flex flex-justify-around" style="width: 100%;">
            <el-input v-model="form.account" placeholder="请输入手机号" autocomplete="off" clearable/>
            <el-button type="primary" plain @click="checkAccount">检测</el-button>
          </div>
        </el-form-item>
        <el-form-item label="账号名称" :label-width="formLabelWidth" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入账号名称" autocomplete="off" clearable/>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择" clearable>
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="show = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showSet" title="设置角色" width="500">
      <el-form :model="form" ref="formRef" :rules="rules">
        <el-form-item label="账号名称" :label-width="formLabelWidth" prop="nickname">
          <el-input v-model="form.nickname" autocomplete="off" readonly/>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择" clearable>
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSet = false">取消</el-button>
          <el-button type="primary" @click="saveUserRole">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup name="user">
  import Table from "@/components/Table/index.vue";
  import Query from "@/components/Query/index.vue";
  import { getAdminUserList, checkTelephone, saveAdminUser } from "@/api/system/admin";
  import { getSysRoleList } from "@/api/system/role";
  import { ref, reactive, toRefs } from "vue";
  import { ElForm } from 'element-plus'


  const formLabelWidth = ref('120px')
  const formRef = ref()
  const form = reactive({
    nickname: '',
    account: '',
    roleId: ''
  })
  const rules = {
    account: [
      { required: true, message: '请输入手机号', trigger: 'blur' }
    ],
    nickname: [
      { required: true, message: '请输入账号名', trigger: 'blur' }
    ],
    roleId: [
      { required: true, message: '请选择角色', trigger: 'change' }
    ]
  }


  const { proxy } = getCurrentInstance()
  const tableData = ref([])
  const total = ref(0)
  const tableLoading = ref(true)
  const loading = ref(false)
  const showDialog = ref(false)

  const show = ref(false)
  const roleList = ref([])
  const checkAccount = () =>{
    if(!form.account){
      proxy.$message.error('请输入手机号')
      return
    }
    checkTelephone(form.account).then(res => {
      if(res.code != 200){
        proxy.$message.error('手机号已存在')
      }else{
        proxy.$message.success('手机号可用')
      }
    })
  }
  const handleAdd = () => {
    show.value = true
  }
  const showSet = ref(false)
  const setRole = (item) => {
    form.id = item.id
    form.nickname = item.nickname
    form.roleId = item.roleId
    showSet.value = true
  }

  const saveUserRole = async () => {
    loading.value = true
        try {
          // 这里调用API进行提交
          await saveAdminUser(form)
          // await new Promise(resolve => setTimeout(resolve, 1000))
          show.value = false // 修改 showDialog 为 show
          showSet.value = false

          getList()
          proxy.$modal.msgSuccess("操作成功")
        } finally {
          loading.value = false
        }
  }
  
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid, fields) => {
      if (valid) {
        loading.value = true
        try {
          // 这里调用API进行提交
          await saveAdminUser(form)
          // await new Promise(resolve => setTimeout(resolve, 1000))
          show.value = false // 修改 showDialog 为 show
          getList()
          proxy.$modal.msgSuccess("操作成功")
        } finally {
          loading.value = false
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  const getSysRole = () => {
    getSysRoleList({}).then(res => {
      if(res.code == 200){
        roleList.value = res.data.records
      }
    })
  }

  getSysRole();


  
  const data = reactive({
   tableColumns: [
     { label: "账号名", prop: "nickname", },
     { label: "登录手机号", prop: "account" },
     { label: "账号角色", prop: "roleName" },
     { label: "加入时间", prop: "gmtCreate", },
     { label: "操作",  prop: "opt", slot: 'opt'},
   ],
   queryColumns: [
     { label: '账号名', prop: 'nickname', type: 'input', attrs: { placeholder: '请输入账号名' } },
     { label: '手机号', prop: 'account', type: 'input', attrs: { placeholder: '请输入手机号' } },
   ],
   pageParams: {
    current: 1,
    size: 10
   },
   queryParams: {},
   formItems: [
     {
       prop: 'account',
       label: '账号名',
       type: 'input',
       placeholder: '请输入账号名'
     },
     {
       prop: 'tele',
       label: '手机号',
       attrs: { maxlength: 11 },
       type: 'input',
       placeholder: '请输入手机号'
     },
     {
       prop: 'status',
       label: '启用状态',
       type: 'switch',
       attrs: {
         activeValue: 1,
         inactiveValue: 0,
         activeColor:"#13ce66",
         inactiveColor:"#ff4949"
       }
     },
   ]
  })
  
  
  const { tableColumns, queryColumns, pageParams, queryParams } = toRefs(data)
  /** 获取列表数据 */
  const getList = () => {
    tableLoading.value = true
    const data  = {
       ...queryParams.value,
       ...pageParams.value
    }
    getAdminUserList(data)
     .then(res => {
         tableData.value = res.data.records
         total.value = res.data.totalRow
     })
     .finally(() => {
         tableLoading.value = false
     })
  }
  getList()
  
  /** 搜索按钮操作 */
  const handleQuery = (val) => {
   queryParams.value = val
   getList()
  }
  const handlePagination = (val) => {
   pageParams.value = val
   getList()
  }

  const changeValue = (row) => {
   proxy.$modal.confirm(`是否移除此用户？`)
   .then(() => {
     saveAdminUser({ id: row.id, delFlag: -1})
     .then(() => {
       proxy.$modal.msgSuccess("操作成功")
       getList()
     })
   })
  }
  
  </script>
  <style lang="scss">
  .app-user {
   padding: 8px;
  }
  </style>